package oceanwiki.controller;

import com.alibaba.fastjson.JSONObject;
import oceanwiki.req.UserLoginReq;
import oceanwiki.req.UserQueryReq;
import oceanwiki.req.UserSaveReq;
import oceanwiki.resp.*;
import oceanwiki.service.IUserService;
import oceanwiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.EventRecodingLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private IUserService userService;

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/list")
    public CommonResp list(@Valid UserQueryReq req) {
        CommonResp<PageResp<UserQueryResp>> resp = new CommonResp<>(true, "查询成功", null);

        PageResp<UserQueryResp> pageResp = userService.listByName(req);

        resp.setContent(pageResp);

        return resp;
    }

    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody UserSaveReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        CommonResp resp = new CommonResp<>(true, "保存成功", null);

        userService.save(req);
        return resp;
    }

    @DeleteMapping("/remove/{id}")
    public CommonResp delete(@PathVariable Long id) {
        CommonResp resp = new CommonResp<>();

        userService.delete(id);

        return resp;
    }

    @GetMapping("/all")
    public CommonResp all() {
        CommonResp<List<UserQueryResp>> resp = new CommonResp<>(true, "保存成功", null);

        List<UserQueryResp> list = userService.all();
        resp.setContent(list);

        return resp;
    }

    @PostMapping("/login")
    public CommonResp login(@Valid @RequestBody UserLoginReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));

        CommonResp<UserLoginResp> resp = new CommonResp<>();

        UserLoginResp userLoginResp = userService.login(req);

        Long token = snowFlake.nextId();

        LOG.info("生成的Token:{}, 放在redis中", token);


        userLoginResp.setToken(token.toString());

        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(userLoginResp), 3600*24, TimeUnit.SECONDS);

        resp.setContent(userLoginResp);

        return resp;
    }
}
